# import cProfile
# 性能分析https://www.cnblogs.com/Simon-xm/p/4171902.html

# 系统相关库
import traceback
from queue import Queue
# UI相关库
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image

from kivy.properties import (
    NumericProperty, StringProperty, ReferenceListProperty, ObjectProperty, ListProperty
)
from kivy.core.text import LabelBase
LabelBase.register('Roboto','./res/fonts/msyh.ttf')# 注册字体
from kivy.graphics.texture import Texture
from kivy.clock import Clock

from kivy.core.window import Window

# 模块库
from ParseGesture import data2userCode
import PoseStream
import globalvar as gv

import cv2

class GestureScreen(BoxLayout):
    
    imgeoutput = ObjectProperty(None)
    poseoutput = ObjectProperty(None)
    splitterbottom = ObjectProperty(None)
    textoutput = ObjectProperty(None)
    scrlv = ObjectProperty(None)
    n = 0
    

    def __init__(self, **kwargs):
        super(GestureScreen, self).__init__(**kwargs)
        # if "config" in kwargs:
        #     self.config = kwargs["config"]
        # 计时器计时更新摄影图像
        # https://blog.csdn.net/weixin_41819529/article/details/105308156
        PoseStream.Gesture_screen=Queue()
        self.VIEW_HANDS=False
        self.clock_event = None
        self.clock_event = Clock.schedule_interval(self.update, 0)
        # Clock.unschedule(self.clock_event)

    # 开始播放摄像图像
    def start(self):
        self.splitterbottom.size_hint[1]=0.7
        self.scrlv.size_hint[1]=0.3
        self.VIEW_HANDS=True

    # 停止播放摄像图像
    def stop(self):
        # 隐藏
        self.splitterbottom.size_hint[1]=0
        # 清空
        texture=Texture.create(size=(1,1), colorfmt='bgr')
        self.imgeoutput.texture=texture      
        self.VIEW_HANDS=False  

    # 更新摄像图像和状态信息
    def update(self, dt):
        if self.VIEW_HANDS:
            frame = None
            while True:
                try:
                    frame = PoseStream.Gesture_screen.get_nowait()
                except:
                    break
            if frame is not None:
                self.imgeoutput.color=(1,1,1,1)
                buf1 = cv2.flip(frame, 0)
                buf = buf1.tobytes()
                texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
                texture1.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
                self.imgeoutput.texture = texture1
        data = gv.get("DATA")
        data = data2userCode(data)
        self.poseoutput.text=""
        for i, d in enumerate(data):
            site = "({:.2f}, {:.2f})".format(*(d[1]))
            self.poseoutput.text+="[{}]姿态：{}\n[{}]坐标：{}\n".format(i, d[0], i, site)
    
    # 写标准输出
    def write(self,s):
        if s and s!='\n':
            text = self.textoutput.text
            if self.n>20:
                pos  = text.find('\n')
                if pos>0:
                    text=text[pos+1:]
            self.textoutput.text=text+"Out[{:>6d}]: {}\n".format(self.n,s)
            self.n+=1
